using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using System;
using System.Linq;

public class GraphNodeInspector : VisualElement
{
    public new class UxmlFactory : UxmlFactory<GraphNodeInspector, VisualElement.UxmlTraits> { }

    private VisualElement mCurrentVisualTree;
    private Editor mEditor;

    private HashSet<GraphNode> mNodeHashSet;
    public GraphNodeInspector()
    {
        var visualTree = Resources.Load<VisualTreeAsset>("UXML/GraphNodeInspector");
        visualTree.CloneTree(this);

        mCurrentVisualTree = null;
        RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);

       
        mNodeHashSet = new HashSet<GraphNode>();
    }

    private void OnAttachToPanel(AttachToPanelEvent e)
    {
        if (mCurrentVisualTree != null)
        {
            mCurrentVisualTree.UnregisterCallback<GraphNodeSelect>(OnGraphNodeSelect);
            mCurrentVisualTree.UnregisterCallback<GraphNodeUnSelect>(OnGraphNodeUnSelect);
            mCurrentVisualTree = null;
        }
        if (e.destinationPanel != null && 
            e.destinationPanel.visualTree != null)
        {
            mCurrentVisualTree = e.destinationPanel.visualTree;
            mCurrentVisualTree.RegisterCallback<GraphNodeSelect>(OnGraphNodeSelect);
            mCurrentVisualTree.RegisterCallback<GraphNodeUnSelect>(OnGraphNodeUnSelect);
        }
    }
    


    private void OnGraphNodeSelect(GraphNodeSelect evt)
    {
        mNodeHashSet.Add(evt.node);
        OnSelectionChange();
    }

    private void OnGraphNodeUnSelect(GraphNodeUnSelect evt)
    {
        mNodeHashSet.Remove(evt.node);
        OnSelectionChange();
    }

    public void OnSelectionChange()
    {
        Clear();

        if (mEditor)
        {
            UnityEngine.Object.DestroyImmediate(mEditor);
            mEditor = null;
        }

        if(mNodeHashSet.Count == 1)
        {
            
            mEditor = Editor.CreateEditor(mNodeHashSet.First().Data);
        }
        
        Add(new IMGUIContainer(() =>
        {
            if (mEditor)
            {
                mEditor.OnInspectorGUI();
            }
        }));
    }
}
